package com.standardoperationapp.materialinventory.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.standardoperationapp.R;
import com.standardoperationapp.bean.BatchNumBean;
import com.standardoperationapp.bean.MatPlanBean;
import com.standardoperationapp.bean.PlanTypeSpinnerBean;
import com.standardoperationapp.databinding.ActivityCommnonBinding;
import com.standardoperationapp.global.GlobalVaries;
import com.standardoperationapp.global.GsonUtils;
import com.standardoperationapp.materialinventory.adapter.MatPlanListAdapter;
import com.standardoperationapp.net.MaterialApi;
import com.standardoperationapp.net.OnSuccessAndFaultListener;
import com.standardoperationapp.net.OnSuccessAndFaultSub;
import com.standardoperationapp.utils.ToastUtil;


import java.util.ArrayList;
import java.util.List;

public class CommnonActivity extends AppCompatActivity {

    private Spinner churuTypeSpinner;
    private Spinner detailTypeSpinner;
    private Spinner biaodanhaoSpinner;
    private ArrayAdapter<String> adapter;
    private ArrayAdapter<String> detailadapter;
    private ArrayAdapter<String> planTypeAdapter;
    private List<String> churuData;
    private Button confirmBtn, cancelBtn;
    private ActivityCommnonBinding binding;
    private MatPlanListAdapter planListAdapter;
    private String churuType;
    private BatchNumBean batchNumBean;
    private BatchNumBean.DataDTO selectBatchNumBean;
    private ArrayList<MatPlanBean.DataDTO.ListDTO> matPlanList;
    private List<String> planTypeList = new ArrayList<>();
    private PlanTypeSpinnerBean planTypeSpinnerBean;
    private int inventTypeId;
    private int pageNum = 1;
    private MatPlanBean matPlanBean;


    //= {"出库","入库","盘点"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_commnon);
//        setContentView(binding.getRoot());
        confirmBtn = (Button) findViewById(R.id.confirmBtn);
        cancelBtn = (Button) findViewById(R.id.cancelBtn);
        churuTypeSpinner = (Spinner) findViewById(R.id.churuTypeSpin);

        detailTypeSpinner = (Spinner) findViewById(R.id.detailTypeSpin);
        biaodanhaoSpinner = (Spinner) findViewById(R.id.biaodanhaoSpin);

        this.churuData = new ArrayList<String>();//实例化集合
        this.churuData.add("出库");
        this.churuData.add("入库");
        this.churuData.add("盘点");

        this.adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, this.churuData);//装配适配器
        this.adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//重新设置风格
        this.churuTypeSpinner.setAdapter(this.adapter);//设置下拉选项

        getMatInventoryType();

        // churuTypeSpinner.setAdapter(adapter);
        // 出入库选择spinner
        churuTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 记录当前选择的项
                churuType = (String) parent.getItemAtPosition(position);
                Log.d("Spinner", "Selected item: " + churuType);
//                com.standardoperationapp.global.TitleBorderLayout layout = findViewById(R.id.titlelayout);

                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.setMargins(20,20,20,20);
                if (churuType.equals("出库")) {
                    GlobalVaries.inOutType = GlobalVaries.outBound;
                    updateDetailSpinnner(GlobalVaries.chukuTypeList);
                    binding.tvContentTitle.setText("关联单据");
                    binding.titlelayout.setLayoutParams(params);
                } else if (churuType.equals("入库")) {
                    GlobalVaries.inOutType = GlobalVaries.inBound;
                    updateDetailSpinnner(GlobalVaries.rukuTypeList);
                    binding.tvContentTitle.setText("关联单据");
                    binding.titlelayout.setLayoutParams(params);

//                    layout.setTitle("关联单据");
                } else if (churuType.equals("盘点")) {
                    GlobalVaries.inOutType = -1;
                            updateDetailSpinnner(GlobalVaries.pankuTypeList);
                    binding.tvContentTitle.setText("关联计划");
                    LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    params1.setMargins(20,20,20,20);
                    binding.titlelayout.setLayoutParams(params1);

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 什么都不做
            }
        });
        // 类型选择spinner
        detailTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 记录当前选择的项
                String selectedItem = (String) parent.getItemAtPosition(position);
                Log.d("detailTypeSpinner", "detailTypeSpinner Selected item: " + selectedItem);
                binding.biaodantTV.setText("");
                if (selectedItem.equals("盘点")) {
                    binding.llPlan.setVisibility(View.VISIBLE);
                    binding.planListView.setVisibility(View.VISIBLE);
                    binding.llDocument.setVisibility(View.GONE);
                    updatePlanTypeSpinner();
                } else {
                    binding.llPlan.setVisibility(View.GONE);
                    binding.planListView.setVisibility(View.GONE);
                    binding.llDocument.setVisibility(View.VISIBLE);
                    // todo 从服务器查询批次号
                    getBatchList(selectedItem);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 什么都不做
            }
        });
        // 批号选择选择spinner
        biaodanhaoSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                selectBatchNumBean = batchNumBean.getData().get(i);
                if (GlobalVaries.uiType == GlobalVaries.KUCUNBUCHONG) {
                    binding.biaodantTV.setText(selectBatchNumBean.getPlanName());
                } else {
                    binding.biaodantTV.setText(selectBatchNumBean.getStorageName());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        // 盘点计划选择spinner
        binding.planTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // 记录当前选择的项
                String selectedItem = (String) parent.getItemAtPosition(position);
                Log.d("Spinner", "Selected item: " + selectedItem);
                inventTypeId = Integer.parseInt(planTypeSpinnerBean.getData().get(position).getId());
                // todo 从服务器查询数据
                if (selectedItem.contains("现场")) {
                    GlobalVaries.uiType = GlobalVaries.XIANCHANGWUZI;
                } else {
                    GlobalVaries.uiType = GlobalVaries.PANDIAN;
                }
                pageNum = 1;
                MaterialApi.getMatInventoryTaskList(inventTypeId, 1, 10, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
                    @Override
                    public void onSuccess(Object result) {
                        matPlanBean = GsonUtils.fromJson(result.toString(), MatPlanBean.class);
                        matPlanList.clear();
                        matPlanList.addAll(matPlanBean.getData().getList());
                        planListAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFault(String errorMsg) {

                    }
                }));


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 什么都不做
            }
        });
        confirmBtn.setOnClickListener(view -> {
            String selectString = detailTypeSpinner.getSelectedItem().toString();
            String titleString = "消耗单";

            Intent intent = new Intent(CommnonActivity.this, DetailActivity.class);
            switch (selectString) {
                case "消耗":
                    intent.putExtra("isSubmit", selectBatchNumBean.getScanStatus() == 1);
                    GlobalVaries.uiType = GlobalVaries.XIAOHAO;
                    titleString = selectString + "单";
                    break;
                case "领用":
                    GlobalVaries.uiType = GlobalVaries.LINGYONG;
                    titleString = selectString + "单";
                    break;
                case "调拨":
                    GlobalVaries.uiType = GlobalVaries.DIAOBO;
                    titleString = selectString + "单";
                    break;
                case "报废":
                    GlobalVaries.uiType = GlobalVaries.baoFei;
                    titleString = selectString + "单";
                    break;
                case "库存补充":
                    intent.putExtra("isSubmit", selectBatchNumBean.getAppStatus() == 1);
                    GlobalVaries.uiType = GlobalVaries.KUCUNBUCHONG;
                    titleString = selectString + "单";
                    break;
                case "盘点":
                    return;
//                        GlobalVaries.uiType = GlobalVaries.PANDIAN;
//                        titleString = selectString + "详情";
                default:
                    break;
            }

            intent.putExtra("title", titleString);
            if (GlobalVaries.uiType == GlobalVaries.KUCUNBUCHONG) {
                intent.putExtra("batchNum", selectBatchNumBean.getPlanMark());
                intent.putExtra("batchName", selectBatchNumBean.getPlanName());
            } else {
                intent.putExtra("batchNum", selectBatchNumBean.getBatchNum());
                intent.putExtra("batchName", selectBatchNumBean.getStorageName());
            }
            intent.putExtra("batchId", selectBatchNumBean.getId() + "");

            startActivity(intent);
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取消哪一层
                finish();
            }
        });
        churuTypeSpinner.setSelection(0);

        binding.refreshLayout.setEnableRefresh(false);
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            loadMoreByMatInventoryTask();
        });

        matPlanList = new ArrayList<>();
        planListAdapter = new MatPlanListAdapter(this, matPlanList);
        View headerView = LayoutInflater.from(this).inflate(R.layout.plan_list_item, binding.planListView, false);
        binding.planListView.addHeaderView(headerView);
        TextView tx1 = headerView.findViewById(R.id.tvNo);
        tx1.setText("序号");
        tx1 = headerView.findViewById(R.id.tvType);
        tx1.setText("物资类型");
        tx1 = headerView.findViewById(R.id.tvTime);
        tx1.setText("盘点时间");
        tx1 = headerView.findViewById(R.id.tvStatus);
        tx1.setText("状态");
        tx1 = headerView.findViewById(R.id.tvFinishTime);
        tx1.setText("完成时间");
        tx1 = headerView.findViewById(R.id.tvClick);
        tx1.setText("操作");
        tx1.setTextColor(Color.BLACK);
        binding.planListView.setAdapter(planListAdapter);
        binding.planListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) return;
                Intent intent = new Intent(CommnonActivity.this, DetailActivity.class);
                intent.putExtra("title", "盘点详情");
                intent.putExtra("batchId", matPlanList.get(i-1).getId());
                intent.putExtra("isSubmit", matPlanList.get(i-1).getStatus() == 1);
//                intent.putExtra("batchNum", selectBatchNumBean.getBatchNum());
//                intent.putExtra("batchName", selectBatchNumBean.getStorageName());

                startActivity(intent);
            }
        });
    }

    private void loadMoreByMatInventoryTask() {
        pageNum++;
        MaterialApi.getMatInventoryTaskList(inventTypeId, pageNum, 10, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {

                binding.refreshLayout.finishLoadMore();
                matPlanBean = GsonUtils.fromJson(result.toString(), MatPlanBean.class);


                matPlanList.addAll(matPlanBean.getData().getList());
                planListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFault(String errorMsg) {
                binding.refreshLayout.finishLoadMore();
            }
        }));
    }

    /**
     * 获取批次号
     */
    private void getBatchList(String val) {
        /**
         *    chukuTypeList.add("领用");
         *             chukuTypeList.add("消耗");
         *             chukuTypeList.add("调拨");
         *             rukuTypeList.add("库存补充");
         */
        OnSuccessAndFaultSub onSuccessAndFaultSub = new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                batchNumBean = GsonUtils.fromJson(result.toString(), BatchNumBean.class);
                if (batchNumBean.getData() == null || batchNumBean.getData().isEmpty()) {
                    ToastUtil.showToast("未查询到关联单据");
                }
                updateBatchNumSpinner();
            }

            @Override
            public void onFault(String errorMsg) {
                ToastUtil.showToast(errorMsg);
            }
        });

        switch (val) {
            case "领用":
                GlobalVaries.uiType = GlobalVaries.LINGYONG;
                if (GlobalVaries.inOutType == GlobalVaries.outBound){
                    MaterialApi.getMatRepertoryBatchNumList(onSuccessAndFaultSub);
                } else {
                    MaterialApi.getInboundBatchNumList(onSuccessAndFaultSub);
                }
                break;
            case "消耗":
                GlobalVaries.uiType = GlobalVaries.XIAOHAO;
                MaterialApi.getMatConsumerBatchNumList(onSuccessAndFaultSub);
                break;
            case "调拨":
                GlobalVaries.uiType = GlobalVaries.DIAOBO;
                if (GlobalVaries.inOutType == GlobalVaries.outBound){
                    MaterialApi.getMatCannibaBatchNumList(GlobalVaries.inOutType, onSuccessAndFaultSub);
                } else {
                    MaterialApi.getMatCannibaBatchNumList(GlobalVaries.inOutType, onSuccessAndFaultSub);
                }
                break;
            case "库存补充":
                GlobalVaries.uiType = GlobalVaries.KUCUNBUCHONG;
                MaterialApi.getPurchasePlanMark(onSuccessAndFaultSub);
                break;
            case "报废":
                GlobalVaries.uiType = GlobalVaries.baoFei;
                MaterialApi.getScrapBatchNumList(GlobalVaries.inOutType, onSuccessAndFaultSub);
                break;
        }
    }

    public void updateDetailSpinnner(List<String> detailData) {

        this.detailadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, detailData);//装配适配器
        this.detailadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//重新设置风格
        this.detailTypeSpinner.setAdapter(this.detailadapter);
    }

    private void getMatInventoryType() {
        MaterialApi.getMatInventoryType(new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
            @Override
            public void onSuccess(Object result) {
                planTypeSpinnerBean = GsonUtils.fromJson(result.toString(), PlanTypeSpinnerBean.class);
                planTypeList= new ArrayList<>();
                for (PlanTypeSpinnerBean.DataDTO datum : planTypeSpinnerBean.getData()) {
                    planTypeList.add(datum.getInventTypeName());
                }

            }

            @Override
            public void onFault(String errorMsg) {

            }
        }));
    }

    public void updatePlanTypeSpinner() {
        List<String> detailData = planTypeList;
        this.planTypeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, detailData);//装配适配器
        this.planTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//重新设置风格
        binding.planTypeSpinner.setAdapter(planTypeAdapter);
    }

    public void updateBatchNumSpinner() {
        List<String> detailData = new ArrayList<>();
        if (batchNumBean.getData() != null) {
            for (BatchNumBean.DataDTO datum : batchNumBean.getData()) {
                if (GlobalVaries.uiType == GlobalVaries.KUCUNBUCHONG) {
                    detailData.add(datum.getPlanMark());
                } else {
                    detailData.add(datum.getBatchNum());
                }
            }
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, detailData);//装配适配器
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//重新设置风格
        biaodanhaoSpinner.setAdapter(adapter);
    }

}